package com.sunnybear.framework.tools;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

/**
 * <p>
 *  2018/5/3.
 */
public class GpsHelper {

    private Context mContext;
    private Receiver receiver;
    private GpsCallback mGpsCallback;
    private String GPS_ACTION = "android.location.PROVIDERS_CHANGED";

    public GpsHelper(Context context, GpsCallback callback) {
        this.mContext = context;
        this.mGpsCallback = callback;

        observeWifiSwitch();
    }

    private void observeWifiSwitch() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(GPS_ACTION);
        receiver = new Receiver();
        mContext.registerReceiver(receiver, filter);
    }

    /**
     * 释放资源
     */
    public void onDestroy() {
        if (receiver != null)
            mContext.unregisterReceiver(receiver);
        if (mContext != null)
            mContext = null;
    }

    class Receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().matches(GPS_ACTION) && mGpsCallback != null)
                mGpsCallback.gpsSwitchState(PhoneUtil.isOpenGPS(context));
        }
    }

    public interface GpsCallback {

        void gpsSwitchState(boolean gpsOpen);
    }
}
